# --*-- coding: UTF-8 --*--
# 本打算封装MSSQL访问类，但是不好用
from . import *

sys.path.append('..')


# 数据库操作对象
class MssqlUtil:
    # 创建连接对象
    @staticmethod
    def getConn():
        conn = None
        try:
            conn = getattr(g, 'conn', None)
            if conn is None:
                conn = g.conn = pyodbc.connect(
                    SQLALCHEMY_DATABASE_URI, unicode_results=True
                )
        except ConnectionError as e:
            print(e)
            return conn
        return conn

    """
    查询数据
    """

    @staticmethod
    def query_data(sql, para=(), flag=False):
        try:
            conn = MssqlUtil.getConn()
            if conn is not None:
                cur = conn.cursor()
                if cur is not None and sql:
                    with cur.execute(sql, para) as result:
                        if flag:
                            row = result.fetchone()
                            if row is not None:
                                return row
                        else:
                            rows = result.fetchall()
                            if rows is not None:
                                return rows
        except Exception as e:
            print(e)
            return None

        return None


    """
    修改和添加数据
    """
    @staticmethod
    def modify_data(sql, para=()):
        try:
            conn = MssqlUtil.getConn()
            if conn is not None:
                cur = conn.cursor()
                if cur is not None and sql:
                    with cur.execute(sql, para) as result:
                        count = result.rowcount
                        if count is not None:
                            return count
        except Exception as e:
            print(e)
            return None
        return None
